package com.zw.yzk.kabu.view.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.CheckBox;

import butterknife.Bind;
import butterknife.OnClick;
import io.rong.imkit.RongIM;
import io.rong.imkit.manager.IUnReadMessageObserver;
import io.rong.imlib.RongIMClient;
import io.rong.imlib.model.Conversation;
import io.rong.push.RongPushClient;
import io.rong.push.common.RongException;

import com.zw.yzk.kabu.R;
import com.zw.yzk.kabu.base.BaseActivity;
import com.zw.yzk.kabu.data.cache.db.DataBaseManager;
import com.zw.yzk.kabu.data.cache.db.User;
import com.zw.yzk.kabu.data.utils.LogUtils;
import com.zw.yzk.kabu.data.utils.SharedPrefrenceUtils;
import com.zw.yzk.kabu.im.IMUtils;
import com.zw.yzk.kabu.im.ImUserUtil;
import com.zw.yzk.kabu.internal.component.DaggerMainComponent;
import com.zw.yzk.kabu.internal.module.ActivityModule;
import com.zw.yzk.kabu.internal.module.RefreshUserInfoModule;
import com.zw.yzk.kabu.jpush.JPushHelper;
import com.zw.yzk.kabu.management.TempData;
import com.zw.yzk.kabu.management.ToastManager;
import com.zw.yzk.kabu.presenter.MainPresenter;
import com.zw.yzk.kabu.view.fragment.DataFragment;
import com.zw.yzk.kabu.view.fragment.ExhibitionFragment;
import com.zw.yzk.kabu.view.fragment.MallFragment;
import com.zw.yzk.kabu.view.fragment.MeFragment;
import com.zw.yzk.kabu.view.view.MainView;

import javax.inject.Inject;

public class MainActivity extends BaseActivity implements MainView{

    @Bind(R.id.cos_page)
    CheckBox cosplay;
    @Bind(R.id.exhibition_page)
    CheckBox exhibition;
    @Bind(R.id.mall_page)
    CheckBox mallPage;
    @Bind(R.id.me_page)
    CheckBox mePage;
    @Bind(R.id.unread)
    public View unread;

    @Inject
    MainPresenter presenter;
    private FragmentManager fragmentManager;
    private DataFragment cosplayFragment;
    private ExhibitionFragment exhibitionFragment;
    private MallFragment mallFragment;
    private MeFragment meFragment;

    @Override
    public int getLayoutId() {
        return R.layout.activity_main;
    }

    @Override
    public void iniToolbar(BaseActivity activity) {
    }

    @Override
    public void initComponent() {
        DaggerMainComponent.builder()
                .applicationComponent(getApplicationComponent())
                .activityModule(new ActivityModule(this))
                .refreshUserInfoModule(new RefreshUserInfoModule())
                .build()
                .inject(this);
        presenter.setView(this);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        checkUpdate();
        refreshUserInfo();
        init();
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);

        checkUpdate();
        refreshUserInfo();
        init();
    }

    @Override
    protected void onResume() {
        super.onResume();
        getUnreadCount();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (presenter != null) {
            presenter.destroy();
        }
    }

    @Override
    public void getUnreadCountSuccess(boolean showRedPoint) {
        boolean show = TempData.getInstance().getUnReaDiMessage() > 0 || showRedPoint;
        if(unread != null) {
            unread.setVisibility(show ? View.VISIBLE : View.GONE);
        }
        if(meFragment != null) {
            meFragment.showMessagePoint(show);
        }
    }

    @Override
    public void refreshUserInfoSuccess() {
        if(meFragment != null) {
            meFragment.setUserInfo();
        }
    }

    @OnClick(R.id.cos_page)
    public void showCosplayPage() {
        changeFragment(0);
    }

    @OnClick(R.id.exhibition_page)
    public void showExhibitionPage() {
        changeFragment(1);
    }

    @OnClick(R.id.mall_page)
    public void showMallPage() {
        changeFragment(2);
    }

    @OnClick(R.id.me_page)
    public void showMePage() {
        //检查是否有未读消息
        getUnreadCount();
        changeFragment(3);
    }


    /**
     * 初始化
     */
    private void init() {
        User user = DataBaseManager.getInstance().getLoginUser();
        if (user != null && user.isLogin()) {
            //连接IM服务器
            IMUtils.connect(SharedPrefrenceUtils.getString(this, SharedPrefrenceUtils.getImToken()), new RongIMClient.ConnectCallback() {
                @Override
                public void onTokenIncorrect() {
                    getImToken();
                }

                @Override
                public void onSuccess(String s) {
                    LogUtils.e("zhanwei", "connect im: " + s);
                    registerImUnreadCount();
                }

                @Override
                public void onError(RongIMClient.ErrorCode errorCode) {
                    ToastManager.getInstance().showToast(MainActivity.this,
                            getResources().getString(R.string.connect_im_server_error) + "(" + errorCode.toString() + ")");
                }
            });
            ImUserUtil.setUserInfo();
        }
        //设置极光推送别名
        JPushHelper.init(this);
        JPushHelper.setAlias(this);
        //初始化默认显示第一个fragment
        changeFragment(0);
    }

    /**
     * 切换fragment
     *
     * @param index 需要显示的页面index
     */
    private void changeFragment(int index) {
        if (index == 3 && !isLogin()) {
            mePage.setChecked(false);
            startActivity(new Intent(this, LoginActivity.class));
            return;
        }
        if (fragmentManager == null) {
            fragmentManager = getSupportFragmentManager();
        }
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        hideFragment(fragmentTransaction);
        switch (index) {
            case 0:
                cosplay.setChecked(true);
                if (cosplayFragment == null) {
                    cosplayFragment = new DataFragment();
                    fragmentTransaction.add(R.id.content, cosplayFragment);
                }
                fragmentTransaction.show(cosplayFragment);
                break;
            case 1:
                exhibition.setChecked(true);
                if (exhibitionFragment == null) {
                    exhibitionFragment = new ExhibitionFragment();
                    fragmentTransaction.add(R.id.content, exhibitionFragment);
                }
                fragmentTransaction.show(exhibitionFragment);
                break;
            case 2:
                mallPage.setChecked(true);
                if (mallFragment == null) {
                    mallFragment = new MallFragment();
                    fragmentTransaction.add(R.id.content, mallFragment);
                }
                fragmentTransaction.show(mallFragment);
                break;
            case 3:
                mePage.setChecked(true);
                if (meFragment == null) {
                    meFragment = new MeFragment();
                    fragmentTransaction.add(R.id.content, meFragment);
                }
                fragmentTransaction.show(meFragment);
                break;
            default:
                break;
        }
        fragmentTransaction.commitAllowingStateLoss();
    }

    /**
     * 隐藏fragment
     *
     * @param transaction transaction
     */
    private void hideFragment(FragmentTransaction transaction) {
        initTab();
        if (cosplayFragment != null) {
            transaction.hide(cosplayFragment);
        }
        if (exhibitionFragment != null) {
            transaction.hide(exhibitionFragment);
        }
        if (mallFragment != null) {
            transaction.hide(mallFragment);
        }
        if (meFragment != null) {
            transaction.hide(meFragment);
        }
    }

    /**
     * 重置tab栏，将所有tab设置为未选中状态
     */
    private void initTab() {
        cosplay.setChecked(false);
        exhibition.setChecked(false);
        mallPage.setChecked(false);
        mePage.setChecked(false);
    }

    /**
     * 检查登录状态，未登录的情况下不进入“我的”页面，而是跳转登录页
     */
    private boolean isLogin() {
        User user = DataBaseManager.getInstance().getLoginUser();
        return !(user == null || !user.isLogin());
    }


    /**
     * 更新个人信息
     */
    public void refreshUserInfo() {
        presenter.refreshUserInfo();
    }

    /**
     * 更新IM token
     */
    private void getImToken() {
        presenter.getImToken();
    }

    /**
     * 获取未读小红点
     */
    public void getUnreadCount() {
        presenter.getUnreadCount();
    }

    /**
     * 获取未读小红点
     */
    public void checkUpdate() {
        presenter.checkUpdate();
    }
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            Intent intent = new Intent(Intent.ACTION_MAIN);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.addCategory(Intent.CATEGORY_HOME);
            startActivity(intent);
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * 添加IM未读消息监听
     */
    private void registerImUnreadCount() {
        if(RongIM.getInstance() != null) {
            RongIM.getInstance().setOnReceiveUnreadCountChangedListener(new RongIM.OnReceiveUnreadCountChangedListener() {
                @Override
                public void onMessageIncreased(int i) {
                    TempData.getInstance().setUnReaDiMessage(i);
                    //是否显示小红点
                    getUnreadCountSuccess(i > 0);
                }
            }, Conversation.ConversationType.PRIVATE);
        }
    }
}
